package cn.itrip.controller;

import cn.itrip.biz.TokenBiz;
import cn.itrip.dao.itripUser.ItripUserMapper;
import cn.itrip.pojo.ItripUser;
import com.alibaba.fastjson.JSONArray;
import common.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/auth")
// 或者方式3：如果不需要发送凭证，则可以保留通配符但禁用凭证
//@CrossOrigin(origins = "*", allowCredentials = "false", allowedHeaders = "*")
public class UserController {

    @Resource
    private ItripUserMapper itripUserMapper;

    @Resource
    private TokenBiz tokenBiz;

    @RequestMapping("/api/dologin")
    @ResponseBody
    public Dto index(HttpServletRequest httpServletRequest, @RequestParam("name") String name, @RequestParam("password") String password) throws Exception {

        String header = httpServletRequest.getHeader("user-agent");

        String md5Password = MD5.getMd5(password, 32);
        System.out.println(md5Password);

        List<ItripUser> all = itripUserMapper.getAll();
        for (int i = 0; i < all.size(); i++) {
            if (all.get(i).getUserCode().equals(name) && all.get(i).getUserPassword().equals(md5Password)) {
                String token = tokenBiz.generateToken(header, all.get(i));
                JredisApi jredisApi = new JredisApi();
                //alibaba哪里的,引用fastjson这个依赖，把类变成json格式
                String jsonString = JSONArray.toJSONString(all.get(i));
                jredisApi.setRedis(token, jsonString, 60 * 60);
                System.out.println(jredisApi);
                ItripTokenVO itripTokenVO = new ItripTokenVO(token, System.currentTimeMillis(), System.currentTimeMillis() + 1000 * 60 * 60); //好像时系统时间以及系统过期时间
                System.out.println(itripTokenVO);
                return DtoUtil.returnDataSuccess(itripTokenVO);
            } else {
                return DtoUtil.returnFail("用户名或密码错误", "10001");
            }
        }
        return DtoUtil.returnFail("用户名或密码错误", "10001");
    }

}
